package com.xaslsoft.xaslsoft.device.rfid.usb.product;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.thread.ThreadUtil;
import com.xaslsoft.xaslsoft.device.rfid.usb.factory.IUsbFactory;
import com.xaslsoft.xaslsoft.device.serial.SerialPortManager;
import gnu.io.SerialPort;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 公司自研读写器
 */
@Component
public class SlUsbRfid implements IUsbFactory {
	SerialPort mSerialPort;

	@Override
	public SerialPort connect(String portName, int baud) {
		ThreadUtil.execute(() -> {
			mSerialPort = SerialPortManager.openSerialPort(portName, baud);
			SerialPortManager.addListener(mSerialPort, true, this::dataAvailable);
		});
		return mSerialPort;
	}

	@Override
	public void sendData(String hexStr) {
		SerialPortManager.sendToPort(mSerialPort, hexStr);
	}

	@Override
	public boolean startRead() {
		TAG_SET.clear();
		TAG_CACHE.clear();
		/**
		 * 使用单次轮询
		 */
		boolean send = SerialPortManager.sendToPort(mSerialPort, "BB00220000227E");
		return send;
	}

	@Override
	public boolean startWrite() {
		return false;
	}

	@Override
	public boolean stopRead() {
		boolean send = SerialPortManager.sendToPort(mSerialPort, "BB00280000287E");
		return send;
	}

	@Override
	public Set<String> onReceiveData(String hex) {
		TAG_SET.add(hex);
		TAG_CACHE.put(KEY_TAG, TAG_SET);
		return TAG_SET;
	}

	@Override
	public void dataAvailable(String hexStr) {
		System.out.println(StrFormatter.format("收到串口{{}}返回数据hexStr======>{}", mSerialPort, hexStr));
		onReceiveData(hexStr);

	}
}
